<template>
  <div class="app-container">
    <el-row :gutter="0">
      <!--部门数据-->
      <el-col :span="4" :xs="24" v-show="isShow">
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :expand-on-click-node="false"
            :default-expanded-keys="expandedKeys"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="spanWidth" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          id="searchFrom"
        >
          <el-form-item>
            <el-input
              v-model="queryParams.searchValue"
              placeholder="姓名/工号/手机"
              clearable
              @keyup.enter="handleQuery"
              style="width: 180px"
            />
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="queryParams.job"
              filterable
              placeholder="选择岗位"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in jobOption"
                :key="dict.postId"
                :label="dict.postName"
                :value="dict.postName"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="queryParams.position"
              placeholder="选择职务"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in rsgl_ygda_position"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="queryParams.employeeStatus"
              placeholder="状态"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in rsgl_ygda_employee_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryParams.checkStatus"
              placeholder="审核状态"
              style="width: 180px"
              @change="currentChange"
            >
              <el-option label="未审核" value="0" />
              <el-option label="已审核" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              start-placeholder="入职开始日期"
              end-placeholder="入职结束日期"
              range-separator="~"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8" style="margin-bottom: 20px">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['rsgl:ygda:handle']"
              type="primary"
              icon="Plus"
              @click="handleAdd"
              >新增员工</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['rsgl:ygda:handle']"
              type="primary"
              plain
              icon="Edit"
              :disabled="single"
              @click="handle('修改部门')"
              >修改部门</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['rsgl:ygda:handle']"
              type="primary"
              plain
              icon="EditPen"
              :disabled="single"
              @click="handle('修改职务')"
              >修改职务</el-button
            >
          </el-col>
          <el-col :span="1.5" v-if="queryParams.checkStatus == 0">
            <el-button
              v-hasPermi="['rsgl:ygda:handle']"
              type="primary"
              plain
              icon="Switch"
              :disabled="multiple"
              @click="handleCheck"
              >审核</el-button
            >
          </el-col>
          <el-col :span="1.5" v-if="queryParams.checkStatus == 1">
            <el-button
              v-hasPermi="['rsgl:ygda:handle']"
              type="primary"
              plain
              icon="Switch"
              :disabled="multiple"
              @click="handleCounteraudit"
              >反审核</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['rsgl:ygda:handle']"
              type="primary"
              plain
              icon="Download"
              :loading="exportLoading"
              @click="queryDownLoadTask"
              >导出数据</el-button
            >
          </el-col>
        </el-row>

        <el-table
          @row-dblclick="dbSelected"
          stripe
          v-loading="loading"
          :data="employeeList"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="姓名"
            prop="employeeName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="部门"
            sortable="true"
            prop="deptName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="岗位"
            sortable="true"
            prop="job"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="岗位类别"
            prop="jobCategory"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="职务"
            sortable="true"
            prop="position"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="账号状态"
            sortable="true"
            prop="accountStatus"
            :show-overflow-tooltip="true"
            width="100"
          >
            <template v-slot="scope">
              <div style="display: flex; align-items: center">
                <span
                  :class="
                    scope.row.accountStatus == 0
                      ? 'node-span-green'
                      : 'node-span-red'
                  "
                ></span>
                <span>
                  {{ scope.row.accountStatus == 0 ? '启用' : '禁用' }}</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="手机"
            prop="mobile"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            label="在职状态"
            sortable="true"
            prop="employeeStatus"
            :show-overflow-tooltip="true"
            width="100"
          >
            <template #default="scope">
              <el-tag :type="getcontractCheckClass(scope.row)">
                <span>
                  {{
                    rsgl_ygda_employee_status.find(
                      item => item.value == scope.row.employeeStatus
                    )
                      ? rsgl_ygda_employee_status.find(
                          item => item.value == scope.row.employeeStatus
                        ).label
                      : ''
                  }}
                </span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="入职时间"
            sortable="true"
            prop="entryCompanyTime"
            width="120"
          />

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="100"
            class-name="small-padding fixed-width"
          >
            <template v-slot="scope">
              <el-dropdown
                size="mini"
                @command="command => handleCommand(command, scope.row)"
              >
                <!-- v-hasPermi="[
                  'rsgl:ygda:xq',
                  'rsgl:ygda:bj',
                  'rsgl:ygda:sz',
                  'rsgl:ygda:sc'
                ]" -->
                <span class="el-dropdown-link">
                  <el-icon><DArrowRight /></el-icon>更多
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <div>
                      <!-- v-hasPermi="['rsgl:ygda:xq']" -->
                      <el-dropdown-item command="handleDetail" icon="View"
                        >详情</el-dropdown-item
                      >
                    </div>
                    <div v-hasPermi="['rsgl:ygda:handle']">
                      <el-dropdown-item
                        command="handleUpdate"
                        icon="Edit"
                        v-if="scope.row.checkStatus != '1'"
                        >编辑</el-dropdown-item
                      >
                    </div>
                    <div v-hasPermi="['system:employee:authority']">
                      <el-dropdown-item command="handleProfession" icon="Edit"
                        >编辑职称</el-dropdown-item
                      >
                    </div>
                    <div v-hasPermi="['rsgl:ygda:handle']">
                      <el-dropdown-item command="handle" icon="Setting"
                        >设置</el-dropdown-item
                      >
                    </div>
                    <div>
                      <!-- v-hasPermi="['rsgl:ygda:history']" -->
                      <el-dropdown-item command="handleHistory" icon="Clock"
                        >历史</el-dropdown-item
                      >
                    </div>
                    <div v-hasPermi="['rsgl:ygda:handle']">
                      <el-dropdown-item
                        command="handleDelete"
                        icon="el-icon-delete"
                        >删除</el-dropdown-item
                      >
                    </div>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <!-- <el-button  v-hasPermi="['rsgl:zzjg:xq']" style="padding: 5px;" size="mini" type="primary" plain icon="el-icon-info"
                                @click="handleDetail(scope.row)">详情</el-button>
                            <el-button  v-hasPermi="['rsgl:zzjg:bj']" style="padding: 5px;" size="mini" type="primary" plain icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">编辑</el-button>
                            <el-button  v-hasPermi="['rsgl:zzjggetListcurrentChange:sz']" style="padding: 5px;" size="mini" type="primary" plain icon="el-icon-setting"
                                @click="handle('设置状态', scope.row)">设置</el-button>
                            <el-button  v-hasPermi="['rsgl:zzjg:sc']" style="padding: 5px;" type="danger" plain v-if="scope.row.parentId != 0"
                                size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="currentChange"
        />
      </el-col>
    </el-row>

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="已选员工:">
          <el-input
            prefix-icon="el-icon-user-solid"
            v-model="curEmployeeName"
            disabled
          />
        </el-form-item>
        <el-form-item
          v-if="dialogTitle == '修改职务'"
          label="选择岗位:"
          prop="job"
        >
          <el-select
            v-model="form.job"
            placeholder="请选择岗位"
            style="width: 100%"
          >
            <el-option
              v-for="dict in jobOption"
              :key="dict.postId"
              :label="dict.postName"
              :value="dict.postName"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="dialogTitle == '修改职务'"
          label="选择职务:"
          prop="position"
        >
          <el-select
            v-model="form.position"
            placeholder="请选择职务"
            style="width: 100%"
          >
            <el-option
              v-for="dict in rsgl_ygda_position"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogTitle == '设置状态'" label="选择状态:">
          <el-radio-group
            v-model="form.employeeStatus"
            @change="changeEmployeeStatus"
          >
            <el-radio
              v-for="(item, index) in rsgl_ygda_employee_status"
              :label="item.value"
              :key="index"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="dialogTitle == '设置状态' && form.employeeStatus == '1'"
          label="实际转正时间"
        >
          <el-input
            v-model="form.turnTime"
            placeholder="请输入实际转正时间YYYY-MM-DD 或 YYYY-MM"
          ></el-input>
          <!-- <el-date-picker
            v-model="form.leaveDate"
            type="date"
            placeholder="请选择离职时间"
            value-format="YYYY-MM-DD"
          /> -->
        </el-form-item>
        <el-form-item
          v-if="dialogTitle == '设置状态' && form.employeeStatus == '2'"
          label="离职时间:"
        >
          <el-input
            v-model="form.leaveDate"
            placeholder="请输入离职时间YYYY-MM-DD 或 YYYY-MM"
          ></el-input>
          <!-- <el-date-picker
            v-model="form.leaveDate"
            type="date"
            placeholder="请选择离职时间"
            value-format="YYYY-MM-DD"
          /> -->
        </el-form-item>

        <el-form-item
          v-if="dialogTitle == '设置状态' && form.employeeStatus == '3'"
          label="预计转正时间:"
        >
          <el-input
            v-model="form.turnTimePlan"
            placeholder="请输入预计转正时间YYYY-MM-DD 或 YYYY-MM"
          ></el-input>
          <!-- <el-date-picker
            v-model="form.leaveDate"
            type="date"
            placeholder="请选择离职时间"
            value-format="YYYY-MM-DD"
          /> -->
        </el-form-item>

        <el-form-item
          v-if="dialogTitle == '设置状态' && form.employeeStatus == '5'"
          label="退休时间:"
        >
          <el-input
            v-model="form.retirementTime"
            placeholder="请输入退休时间YYYY-MM-DD 或 YYYY-MM"
          ></el-input>
          <!-- <el-date-picker
            v-model="form.leaveDate"
            type="date"
            placeholder="请选择离职时间"
            value-format="YYYY-MM-DD"
          /> -->
        </el-form-item>

        <el-form-item
          v-if="dialogTitle == '设置状态' && form.employeeStatus == '4'"
          label="实习时间起:"
        >
          <el-input
            v-model="form.internshipBeginTime"
            placeholder="请输入实习时间起YYYY-MM-DD 或 YYYY-MM"
          ></el-input>
          <!-- <el-date-picker
            v-model="form.leaveDate"
            type="date"
            placeholder="请选择离职时间"
            value-format="YYYY-MM-DD"
          /> -->
        </el-form-item>
        <el-form-item
          v-if="dialogTitle == '设置状态' && form.employeeStatus == '4'"
          label="实习时间止:"
        >
          <el-input
            v-model="form.internshipEndTime"
            placeholder="请输入实习时间止YYYY-MM-DD 或 YYYY-MM"
          ></el-input>
          <!-- <el-date-picker
            v-model="form.leaveDate"
            type="date"
            placeholder="请选择离职时间"
            value-format="YYYY-MM-DD"
          /> -->
        </el-form-item>

        <el-form-item
          v-if="dialogTitle == '修改部门'"
          label="选择部门:"
          prop="deptId"
        >
          <!--          <treeselect-->
          <!--            v-model="form.deptId"-->
          <!--            :options="deptOptionsT"-->
          <!--            :show-count="true"-->
          <!--            placeholder="请选择部门"-->
          <!--            :disable-branch-nodes="true"-->
          <!--          />-->
          <el-tree-select
            style="width: 100%"
            v-model="form.deptId"
            :data="deptOptionsT"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            placeholder="请选择部门"
            value-key="id"
            filterable
          />
        </el-form-item>
        <el-form-item label="备注内容:">
          <el-input
            rows="6"
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
    <historyForm
      v-if="isHistory"
      :rowId="rowId"
      @closeDialog="closeDialog"
    ></historyForm>

    <!-- 导出列表框 -->
    <el-dialog
      title="导出"
      v-model="showExportTask"
      width="600"
      @close="closeInterval"
    >
      <el-row
        v-for="item in downloadTaskList"
        :key="item.fileId"
        class="my-20px taskList"
      >
        <el-col :span="8">{{ item.createTime }}</el-col>
        <el-col :span="3">{{
          item.state == '1' ? '下载完成' : '下载中'
        }}</el-col>
        <el-col :span="4" v-if="item.state === '1' && item.url">
          <a :href="item.url" class="color-#4a9eff" download>下载</a></el-col
        >
      </el-row>
      <template #footer>
        <div>
          <el-button type="primary" @click="handleExport">新建任务</el-button>
          <el-button @click="closeExportTask">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="编辑职称" v-model="showEditJobTitle">
      <el-form :model="jobTitleForm" inline>
        <el-row>
          <el-col :span="10" :offset="2">
            <el-form-item label="姓名：">
              <el-input v-model="jobTitleForm.employeeName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="部门：">
              <el-input v-model="jobTitleForm.deptName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10" :offset="2">
            <el-form-item label="VPN：">
              <el-select
                placeholder="VPN"
                v-model="jobTitleForm.vpn"
                style="width: 180px"
                clearable
              >
                <el-option value="0" label="否"></el-option>
                <el-option value="1" label="是"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="分类：">
              <el-select
                placeholder="分类"
                v-model="jobTitleForm.classes"
                style="width: 180px"
                clearable
              >
                <el-option
                  v-for="item in rsgl_classes"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="10" :offset="2">
            <el-form-item label="职类：">
              <el-select
                placeholder="职类"
                v-model="jobTitleForm.jobType"
                style="width: 180px"
                clearable
              >
                <el-option
                  v-for="item in rgsl_job_type"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="10">
            <el-form-item label="职称：">
              <el-select
                placeholder="职称"
                v-model="jobTitleForm.jobTitle"
                style="width: 180px"
                multiple
                clearable
              >
                <el-option
                  v-for="item in rgsl_job_title"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="confirm">确认</el-button>
        <el-button @click="close">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RsglYgda">
import { treeselect } from '@/api/rsgl/zzjg'
import { listEmployee, delDept } from '@/api/rsgl/ygda'
import {
  listJob,
  employeeCheck,
  setCompany,
  exportEmployee,
  getExportList,
  setEmployeeInfo
} from '@/api/rsgl/ygda'
import { getCurrentInstance, reactive, toRefs, watch } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import historyForm from './history.vue'
const { proxy } = getCurrentInstance()
const router = useRouter()
const isShow = ref(true)
const spanWidth = ref(20)
const data = reactive({
  employeeStatusList: [],
  isHistory: false,
  rowId: '',
  deptId: '',
  expandedKeys: [100], //某个节点展开
  sortObj: null,
  curEmployeeName: null,
  curRow: {},
  jobOption: [], //岗位
  dialogTitle: '',
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 用户表格数据
  employeeList: null,
  // 部门树选项
  deptOptions: undefined,
  deptOptionsT: undefined,
  // 是否显示弹出层
  open: false,
  // 日期范围
  dateRange: [],

  // 表单参数
  form: {
    deptId: undefined,
    status: '0',
    remark: undefined
  },

  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    job: undefined,
    searchValue: undefined,
    position: undefined,
    employeeStatus: '1',
    deptId: undefined,
    checkStatus: '1'
  },

  // 表单校验
  rules: {
    job: [{ required: true, message: '请选择岗位', trigger: 'blur' }],
    position: [{ required: true, message: '请选择职务', trigger: 'blur' }],
    deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }]
  }
})

const {
  employeeStatusList,
  isHistory,
  rowId,
  expandedKeys,
  deptId,
  sortObj,
  curEmployeeName,
  curRow,
  jobOption, //岗位
  dialogTitle,
  // 遮罩层
  loading,
  // 导出遮罩层
  exportLoading,
  // 选中数组
  ids,
  // 非单个禁用
  single,
  // 非多个禁用
  multiple,
  // 显示搜索条件
  showSearch,
  // 总条数
  total,
  // 用户表格数据
  employeeList,
  // 部门树选项
  deptOptions,
  deptOptionsT,
  // 是否显示弹出层
  open,
  // 日期范围
  dateRange,
  // 表单参数
  form,
  // 查询参数
  queryParams,
  // 表单校验
  rules
} = toRefs(data)

const {
  rsgl_ygda_position,
  rsgl_ygda_employee_status,
  rsgl_classes,
  rgsl_job_type,
  rgsl_job_title
} = proxy.useDict(
  'rsgl_ygda_position',
  'rsgl_ygda_employee_status',
  'rsgl_classes',
  'rgsl_job_type',
  'rgsl_job_title'
)
const userStore = useUserStore()
const route = useRoute()

watch(
  () => route.query.deptId,
  val => {
    if (route.query.deptId) {
      console.log('route.query.deptId==', route.query.deptId)
      queryParams.value.deptId = route.query.deptId
      init()
    }
  },
  {
    deep: true,
    immediate: true
  }
)

//员工状态颜色
function getcontractCheckClass(row) {
  let c = ''
  switch (row.employeeStatus) {
    case '1':
      c = ''
      break
    case '2':
      c = 'danger'
      break
    case '3':
      c = 'warning'
      break
    case '4':
      c = 'info'
      break
    case '5':
      c = 'success'
      break
    case '6':
      c = 'info'
      break
  }
  return c
}

function currentChange(item) {
  var orderBy = sortObj.value ? sortObj.value : undefined
  getList(orderBy)
}

/** 查询用户列表 */
function getList(orderBy) {
  loading.value = true
  let param = { ...queryParams.value, orderBy }
  param.beginDate = dateRange.value != null ? dateRange.value[0] : ''
  param.endDate = dateRange.value != null ? dateRange.value[1] : ''
  listEmployee(param).then(response => {
    employeeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function sortChange(column) {
  console.log('column', column)
  var orderBy = ''
  if (column) {
    if (column.order === 'ascending') {
      //这里双重判断：该字段为升序时向后端传递升序参数，反之降序
      orderBy = column.prop + ' asc'
    } else if (column.order === 'descending') {
      orderBy = column.prop + ' desc'
    }
    sortObj.value = orderBy
    getList(orderBy)
  }
}

/** 查询部门下拉树结构 */
function getTreeselect() {
  treeselect().then(response => {
    deptOptions.value = response.data
    console.log(' deptOptions.value ===', deptOptions.value)
    console.log(' deptOptions.value ===', deptOptions.value[0].children)
    if (
      deptOptions.value[0].children == undefined ||
      deptOptions.value[0].children == null
    ) {
      isShow.value = false
      spanWidth.value = 24
    }
  })
}

// 筛选节点
function filterNode(value, data) {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

// 节点单击事件
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  getList()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    deptId: undefined,
    status: '0',
    remark: undefined
  }
  proxy.resetForm('form')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    job: undefined,
    searchValue: undefined,
    position: undefined,
    employeeStatus: '1',
    deptId: undefined,
    checkStatus: '1'
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.employeeId)
  employeeList.value.forEach(element => {
    if (element.employeeId == ids.value[0]) {
      curRow.value = element
      var position = element.position ? ' / ' + element.position : ''
      curEmployeeName.value =
        element.employeeName + '  ' + element.deptName + position
    }
  })
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  router.push({
    path: '/rsgl/rs/addOrUpdateYgda',
    query: { flag: 'add' }
  })
}

/** 详情按钮操作 */
function handleDetail(row) {
  router.push({
    path: '/rsgl/rs/detailYgda',
    query: { employeeId: row.employeeId }
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  router.push({
    path: '/rsgl/rs/editYgda',
    query: { flag: 'update', employeeId: row.employeeId }
  })
}

const showEditJobTitle = ref(false)
const jobTitleForm = ref({})
function confirm() {
  if (
    jobTitleForm.value.employeeId &&
    (jobTitleForm.value.vpn ||
      jobTitleForm.value.classes ||
      jobTitleForm.value.jobType ||
      jobTitleForm.value.jobTitle)
  ) {
    const params = {
      employeeId: jobTitleForm.value.employeeId,
      vpn: jobTitleForm.value.vpn || '',
      classes: jobTitleForm.value.classes || '',
      jobType: jobTitleForm.value.jobType || '',
      jobTitle: jobTitleForm.value.jobTitle.toString() || ''
    }
    setEmployeeInfo(params).then(res => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('修改成功')
        close()
        handleQuery()
      }
    })
  } else {
    close()
  }
}

function close() {
  showEditJobTitle.value = false
}
// 修改职称
function handleProfession(row) {
  console.log(row)
  showEditJobTitle.value = true
  jobTitleForm.value = {
    employeeId: row.employeeId,
    vpn: row.vpn,
    classes: row.classes,
    jobType: row.jobType,
    jobTitle: row.jobTitle ? row.jobTitle.split(',') : [],
    deptName: row.deptName,
    employeeName: row.employeeName
  }
}
// 修改职称
// function edit
//操作记录
function handleHistory(row) {
  isHistory.value = true
  rowId.value = row.employeeId
}
function closeDialog() {
  isHistory.value = false
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      if (dialogTitle.value === '设置状态') {
        // 时间格式校验
        const timeId = [
          'turnTime',
          'leaveDate',
          'turnTimePlan',
          'retirementTime',
          'internshipBeginTime',
          'internshipEndTime'
        ]
        const checkResult = checkDate(timeId)
        if (!checkResult) {
          proxy.$modal.msgWarning('时间格式不正确，请重新输入')
          return
        }
        // 实习时间判断
        if (
          form.value.employeeStatus === '4' &&
          form.value.internshipBeginTime &&
          form.value.internshipEndTime &&
          new Date(form.value.internshipBeginTime).getTime() -
            new Date(form.value.internshipEndTime).getTime() >
            0
        ) {
          proxy.$modal.msgError('实习结束时间不能小于开始时间')
          return
        }
      }
      setCompany(form.value).then(response => {
        proxy.$modal.msgSuccess('操作成功')
        open.value = false
        getList()
      })
    }
  })
}

// 时间格式校验
function checkDate(ids) {
  const format = [
    /^\d{4}-((0[1-9])|(1[012]))-((0[1-9])|((1|2)[0-9])|(3(0|1)))$/,
    /^\d{4}-((0[1-9])|(1[012]))$/
  ]
  let result
  for (let index = 0; index < ids.length; index++) {
    const key = ids[index]
    const val = form.value[key]
    if (val) {
      result = format[0].test(val) || format[1].test(val)
      if (!result) {
        return false
      }
    }
  }

  return true
}

// 更多操作触发
function handleCommand(command, row) {
  switch (command) {
    case 'handleDetail':
      handleDetail(row)
      break
    case 'handle':
      handle('设置状态', row)
      break
    case 'handleUpdate':
      handleUpdate(row)
      break
    case 'handleDelete':
      handleDelete(row)
      break
    case 'handleHistory':
      handleHistory(row)
      break
    case 'handleProfession':
      handleProfession(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy
    .$confirm('是否确定删除数据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      console.log(row.employeeId, 'employeeId')
      return delDept(row.employeeId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy
    .$confirm('是否确认导出相关人员记录？', '操作确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      icon: 'QuestionFilled',
      type: 'warning'
    })
    .then(() => {
      // proxy.downLoadByUrl('/system/employee/export', queryParams.value)
      const params = {
        loginUserId: userStore.user.userId,
        fileType: 'ygda',
        ...queryParams.value
      }
      exportEmployee(params).then(response => {
        // console.log(response)
        proxy.$modal.msgSuccess('新建导出任务成功,请耐心等待导出完成')
        queryDownLoadTask()
      })
    })
}

const cacheTime = ref({})
const employeeStatu = ref([
  {
    value: '1',
    label: '在职',
    id: 'turnTime'
  },
  {
    value: '2',
    label: '离职',
    id: 'leaveDate'
  },
  {
    value: '3',
    label: '试用期',
    id: 'turnTimePlan'
  },
  {
    value: '4',
    label: '实习开始',
    id: 'internshipBeginTime'
  },
  {
    value: '4',
    label: '实习结束',
    id: 'internshipEndTime'
  },
  {
    value: '5',
    label: '退休',
    id: 'retirementTime'
  }
])
function changeEmployeeStatus(val) {
  employeeStatu.value.forEach(item => {
    if (cacheTime.value[item.id]) {
      form.value[item.id] = cacheTime.value[item.id]
    }
  })
}

function handle(title, row) {
  form.value = {
    deptId: null,
    employeeId: null,
    employeeStatus: null,
    job: null,
    position: null,
    remark: null
  }
  dialogTitle.value = title
  open.value = true
  console.log(curRow)

  if (title == '修改部门') {
    console.log(curRow.value.companyId)
    treeselect({ deptId: curRow.value.companyId }).then(response => {
      deptOptionsT.value = response.data
      form.value.deptId = curRow.value.deptId
    })
  }

  console.log(row)
  // 设置按钮
  if (row) {
    var position = row.position ? ' / ' + row.position : ''
    curEmployeeName.value = row.employeeName + '  ' + row.deptName + position
    form.value.employeeId = row.employeeId
    form.value.employeeStatus = row.employeeStatus
    form.value.remark = row.remark
    if (row.employeeStatus < 6) {
      employeeStatu.value.forEach(v => {
        form.value[v.id] = row[v.id]
        cacheTime.value[v.id] = row[v.id]
      })
    }
  } else {
    form.value.employeeId = curRow.value.employeeId
    form.value.remark = curRow.value.remark
  }
}

// 提交审核 --反审核
function handleCheck() {
  console.log(ids.value[0])
  let employeeId = ids.value.toString()
  // let curCheckStatus = null

  // employeeList.value.forEach(element => {
  //   if (element.employeeId == employeeId) {
  //     curCheckStatus = element.checkStatus
  //   }
  // })

  // if (curCheckStatus == '0') {
  proxy
    .$confirm('是否确认提交审核?', '操作确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      icon: 'QuestionFilled',
      type: 'warning'
    })
    .then(() => {
      let sendData = { checkStatus: '1', employeeId }
      employeeCheck(sendData).then(response => {
        proxy.$modal.msgSuccess('审核成功')
        getList()
      })
    })
  // } else {
  //   proxy.$alert('请选择未审核的员工档案', '提示', {
  //     dangerouslyUseHTMLString: true
  //   })
  // }
}
// 反审核
function handleCounteraudit() {
  console.log(ids.value[0])
  let employeeId = ids.value.toString()
  // let curCheckStatus = null

  // employeeList.value.forEach(element => {
  //   if (element.employeeId == employeeId) {
  //     curCheckStatus = element.checkStatus
  //   }
  // })
  // if (curCheckStatus == '1') {
  proxy
    .$confirm('是否确认提交反审核?', '操作确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      icon: 'QuestionFilled',
      type: 'warning'
    })
    .then(() => {
      let sendData = { checkStatus: '0', employeeId }
      employeeCheck(sendData).then(response => {
        proxy.$modal.msgSuccess('反审核成功')
        getList()
      })
    })
  // } else {
  //   proxy.$alert('请选择已审核的员工档案', '提示', {
  //     dangerouslyUseHTMLString: true
  //   })
  // }
}
// 表格双击按钮
function dbSelected(row) {
  router.push({
    path: '/rsgl/rs/detailYgda',
    query: { employeeId: row.employeeId }
  })
}
function init() {
  // 岗位
  listJob().then(response => {
    jobOption.value = response.data
  })
  const deptId = userStore.user.deptId
  expandedKeys.value.push(deptId)
  getList()
  getTreeselect()
  clearInterval(timer.value)
}

// 导出任务弹出
const showExportTask = ref(false)
function closeExportTask() {
  showExportTask.value = false
}

const downloadTaskList = ref([])
function queryDownLoadTask() {
  showExportTask.value = true
  if (timer.value) {
    clearInterval(timer.value)
  }
  getExportList({ createId: userStore.user.userId, type: 'ygda' }).then(res => {
    console.log(res, '返回')
    downloadTaskList.value = res.data
    if (res.data.find(v => v.state == 0)) {
      console.log('空')
      setIntervalQuery(3000, 30)
    }
  })
}

const timer = ref(null)
//设置定时查询下载列表
/**
 *  @params delay 延迟时间
 *  @params num 查询次数
 *  @params unitlClose 关闭弹窗后关闭定时器， true时num无效
 * */
function setIntervalQuery(delay = 3000, num = 30) {
  console.log(123333, timer.value)
  timer.value = setInterval(() => {
    getExportList({ createId: userStore.user.userId, type: 'ygda' })
      .then(res => {
        console.log(res, '返回')
        downloadTaskList.value = res.data
        if (!res.data.find(v => v.state == '0')) {
          clearInterval(timer.value)
        }
      })
      .finally(() => {
        num--
        if (num == 0) {
          clearInterval(timer.value)
        }
      })
  }, delay)
}

function closeInterval() {
  if (timer.value) {
    console.log('clear', timer.value)
    clearInterval(timer.value)
    timer.value = null
  }
}

init()
</script>

<style lang="scss" scoped>
::v-deep {
  .el-table__row {
    // cursor: pointer;
  }
  .el-table tr {
    cursor: pointer;
  }
  .el-message-box__title {
    font-size: 16px;
  }
}
:deep(.el-message-box__title) {
  font-size: 16px;
}
#searchFrom {
  :deep .el-form-item {
    margin-right: 10px;
  }
}
.taskList {
  .el-col {
    display: flex;
    align-items: center;
  }
}
</style>
